extends Node2D

@onready var tele_portation_point: Node2D = %TelePortationPoint

@onready var first_portal: Portal = $FirstPortal
@onready var second_portal: Portal = $SecondPortal

# 游戏状态
enum GameState {
	IDLE,
	FIRST_CHOICE,
	SECOND_CHOICE,
	REWARD,
	FAILED
}

var current_state = GameState.IDLE
var correct_portal_index: int  # 存储正确的传送门

# 奖励配置
var rewards = [200, 400, 800]
var current_reward = 0

func _ready() -> void:
	EventBus.subscribe("to_des", on_to_des)
	EventBus.subscribe("portal_selected", on_portal_selected)

func on_to_des(_name):
	## 首次进入
	if _name == "select_portal":
		RaffleManager.select_portal_count -= 1
		current_state = GameState.FIRST_CHOICE
		Utils.player.global_position = tele_portation_point.global_position
		_reset_portals()
	## 第一次选对
	if _name == "select_portal_second":
		current_state = GameState.SECOND_CHOICE
		Utils.player.global_position = tele_portation_point.global_position
		_reset_portals()

	
func on_portal_selected(portal_index: int):
	match current_state:
		GameState.FIRST_CHOICE:
			_handle_first_choice(portal_index)
		GameState.SECOND_CHOICE:
			_handle_second_choice(portal_index)

## 处理第一次选择
func _handle_first_choice(portal_index: int):
	if portal_index == correct_portal_index:
		EventBus.push_event("to_des", ["select_portal_second"])
	else:
		EventBus.push_event("to_des", ["main_scene"])
		print("第一次选择错误")
		
## 处理第二次选择
func _handle_second_choice(portal_index: int):
	if portal_index == correct_portal_index:
		EventBus.push_event("to_des", ["main_scene"])
		give_reward()
	else:
		EventBus.push_event("to_des", ["main_scene"])
		print("第二次选择错误")

func _reset_portals():
	# 随机生成正确的传送门组合
	correct_portal_index = randi() % 2

func give_reward():
	var rng = RandomNumberGenerator.new()
	## 获取得到的金币
	var get_gold = rewards[rng.rand_weighted([0.5, 0.3, 0.2])]
	Utils.set_player_stats_value("gold", rewards[rng.rand_weighted([0.5, 0.3, 0.2])])
	var message = "获得奖励: %d金币" % get_gold
	Utils.show_string_label_c(message, Utils.player, Color.YELLOW)
	print(message)
